import {
  getJwt,
  removeJwt
} from './jwt.js';
import {
  serverApi
} from './config.js';

const fetch = ({
  url = '/',
  method = 'GET',
  data = {},
  header = {},
  timeout = 60000,
  dataType = 'json',
  responseType = "text",
  toast = true
}) => {
  return new Promise((resolve, reject) => {
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    if (!hasContentTypeHeader(header)) {
      header['Content-Type'] = method === 'POST' ? 'application/x-www-form-urlencoded' : 'application/json';
    }
    header['Authorization'] = "Bearer " + getJwt();
    wx.request({
      method,
      url: serverApi + url,
      data,
      header,
      timeout,
      dataType,
      responseType,
      success: (res) => {
        wx.hideLoading();
        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            resolve(res.data);
          } else {
            if (toast) {
              wx.showToast({
                title: res.data.message,
                icon: "error"
              });
            }
            reject(res.data);
          }
        } else if (res.statusCode === 401) {
          if (toast) {
            wx.showToast({
              title: "登录失效",
              icon: "error"
            })
          }
          removeJwt();
          reject({
            code: res.statusCode,
            message: "登录失效"
          });
        } else {
          if (toast) {
            wx.showToast({
              title: "错误，请重试",
              icon: "error"
            })
          }
          reject({
            code: res.statusCode,
            message: "错误，请重试"
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        if (toast) {
          wx.showToast({
            title: "网络错误",
            icon: "error"
          })
        }
        reject({
          code: err.errno,
          message: "网络错误"
        });
      }
    })
  })
}

/**
 * header中是否存在Content-Type
 */
function hasContentTypeHeader(headers) {
  return !!headers && Object.keys(headers).some(key => key.toLowerCase() === 'content-type');
}

wx.fetch = fetch;

export default fetch;